package cn.nexttec.noteplayer.ui.widget


import android.text.Editable
import android.text.InputFilter
import android.text.InputType
import android.text.TextWatcher
import android.view.KeyEvent
import android.view.MotionEvent
import android.widget.EditText

object PasswordInputHelper {
    fun attachInputs(editTexts: List<EditText>, onFullInput: (String) -> Unit) {
        editTexts.forEachIndexed { index, editText ->
            editText.inputType = InputType.TYPE_CLASS_NUMBER
            editText.filters = arrayOf(InputFilter.LengthFilter(1))

            editText.addTextChangedListener(object : TextWatcher {
                override fun afterTextChanged(s: Editable?) {
                    if (s?.length == 1 && index < editTexts.size - 1) {
                        editTexts[index + 1].requestFocus()
                    }

                    val input = editTexts.joinToString("") { it.text.toString() }
                    if (input.length == editTexts.size) {
                        onFullInput(input)
                    }
                }

                override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}
                override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {}
            })

            editText.setOnKeyListener { _, keyCode, event ->
                if (event.action == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_DEL) {
                    if (editText.text.isEmpty() && index > 0) {
                        editTexts[index - 1].apply {
                            setText("")
                            requestFocus()
                        }
                    }
                }
                false
            }

            editText.setOnTouchListener { _, event ->
                if (event.action == MotionEvent.ACTION_UP) {
                    editText.setSelection(0)
                }
                false
            }
        }
    }
}
